//
//  WXStatusViewModel.swift
//  weibo
//
//  Created by 王旭 on 16/4/20.
//  Copyright © 2016年 王旭. All rights reserved.
//

//---对应WXHomeTableViewController

import UIKit
import SDWebImage

class WXStatusListViewModel: NSObject {
    
    //定义存放微博的数组
//    var statusArray : [WXStatusModel]?
    var statusArray : [WXStatusViewModel]?
    
    //加载数据
    func loadData(isPullup:Bool,finished:(isSuccess:Bool,count:Int)->()) {
        //定义最下面微博的id
        var max_id:Int64 = 0
        //定义最下面微博的id
        var since_id:Int64 = 0
        
        if isPullup {
            max_id = statusArray?.last?.status?.id ?? 0
            
            if max_id == 0{
                max_id--
            }
        }else{
            since_id = statusArray?.first?.status?.id ?? 0
        }
        
        //1.请求地址https://api.weibo.com/2/statuses/home_timeline.json
        let requestUrlStr =  "https://api.weibo.com/2/statuses/home_timeline.json"
        
        
        //2.Get请求所需参数
        let parameters = [
            "access_token":WXUserAccountViewModel.sharedUserAccountViewModel.accessToken ?? "",
            "max_id":"\(max_id)",
            "since_id":"\(since_id)"
        ]
        //3.发送Get请求
        WXNetworkTools.sharedTools.request(.Get, urlString: requestUrlStr, parameters: parameters) { (responseObject, error) -> () in
            //判断返回的的数据是否为空
            if error != nil {
                print("网络错误")
                finished(isSuccess: false,count: 0)
                return
            }
            //判断返回的是否是字典--不能转为字典进入
            guard let resp = responseObject as? [String:AnyObject] else{
                print("返回的不是字典")
                finished(isSuccess: false,count: 0)
                return
            }
            //取出字典中statuses的数据(字典数组)
            guard let dic = resp["statuses"] as? [[String:AnyObject]] else{
                print("取出数据失败")
                finished(isSuccess: false,count: 0)
                return
            }
            //已经成功取出数据到dic,字典转模型
             //临时数组
//            var tempArr = [WXStatusModel]()
            var tempArr = [WXStatusViewModel]()

            //字典转模型
            for value in dic {
                
//                let status = WXStatusModel(dic: value)
//                tempArr.append(status)
                
                let status = WXStatusModel(dic: value)
                let statusViewModel = WXStatusViewModel()
                statusViewModel.status = status
                tempArr.append(statusViewModel)
                
                // 测试-->转发中配图的
//                if status.retweeted_status != nil {
//                    print(status)
//                }
                
                
            }
            //把模型数组交给属性
//            self.statusArray = tempArr
//            print(tempArr)
//            finished(isSuccess: true)
            //缓存单张图片
            self.cacheSinglePhoto(tempArr, finished: finished)
            
            
            if self.statusArray == nil {
                self.statusArray = [WXStatusViewModel]()
            }
            
            if isPullup {
                self.statusArray = self.statusArray! + tempArr
            }else{
                self.statusArray = tempArr + self.statusArray!
            }
            
        }
    }
    
    //缓存单张图片
    private func cacheSinglePhoto(array:[WXStatusViewModel], finished:((isSuccess:Bool,count:Int)->())) {
        
        //创建调度组
        let group = dispatch_group_create()
        
        for value in array {
            //获取到图片地址
            let originPhotoUrls = value.status?.pic_urls
            let retweetPhotoUrls = value.status?.retweeted_status?.pic_urls
            //判断原创是否为空
            let photoUrls =  (originPhotoUrls == nil || originPhotoUrls!.count == 0) ? retweetPhotoUrls : originPhotoUrls

//            let queue = dispatch_get_main_queue()
            //是否为单张图
            if photoUrls?.count == 1 {
//                print("单图")
                //获取下载地址
                let photoUrlStr = photoUrls?.first?.thumbnail_pic
//                print(photoUrlStr)
                //入组
                dispatch_group_enter(group)
                //下载
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: photoUrlStr!), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    //下载完成就更新图片大小
                    value.updatePhotoSingleSize()
                    //出调度组
                    dispatch_group_leave(group)
                })
            }
        }
        
        //调度组内任务全部执行完毕
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            finished(isSuccess: true,count: array.count)
        }

    }

}
